<?php
$db = Db::getInstance();
$accountId = Authenticate::getId();
$query = "SELECT COUNT(*) as c1 FROM Invoice WHERE accountId='{$accountId}' AND packageId='16'";
$result = $db->query($query);
if(!$result){
	throw new Exception();
}
$arr = $result->fetch_assoc();
if($arr['c1']>0){
	View::display('message', array('message'=>'คุณได้สมัคร hosting เพื่อการศึกษาไปแล้ว', 'redir'=> 'old.php', 'sec'=> 4));
	exit();
}

if($_SERVER['REQUEST_METHOD']=='POST'){
	$db->autocommit(false);
	try {
		$dateDue = new DateTime();
		$dateDue->add(new DateInterval('P7D'));
		$dateDue = $dateDue->format('Y-m-d');
		$query = "INSERT INTO Invoice(packageId, dateDue, accountId, isNew, type, status, month) VALUES('16', '{$dateDue}', '{$accountId}', '1', 'hosting', 2, 6)";
		if(!$db->query($query)){
			throw new Exception($db->error);
		}
		$id = $db->insert_id;
		$query = sprintf("INSERT INTO InvoiceHosting(id, domain, serverName) VALUES('{$id}', '%s', '')",
			$db->real_escape_string($_POST['domain']));
		if(!$db->query($query)){
			throw new Exception($db->error);
		}
		if(!isset($_FILES['card']) || $_FILES['card']['error']!=0){
			throw new Exception('กรุณา upload เอกสารยืนยันการเป็นนักศึกษาด้วยค่ะ');
		}
		
		$extension = strtolower(pathinfo($_FILES['card']['name'], PATHINFO_EXTENSION));
		$allowed =  array('gif', 'png', 'jpg');
		if(!in_array($extension, $allowed)){
			throw new Exception('อนุญาติให้ upload ได้แค่ (gif, png, jpg)', 300);
		}
		
		list($width, $height) = getimagesize($_FILES['card']['tmp_name']);
		if($width > 800 || $height > 800){
			throw new Exception('อนุญาติให้รูปกว้างไม่เกิน 800px สูงไม่เกิน 600px', 300);
		}
		
		$fileName = Authenticate::getId().'.'.$extension;
		$query = sprintf("UPDATE Account SET cardEdu='%s' WHERE id='%s'", $db->real_escape_string($fileName), Authenticate::getId());
		if(!$db->query($query)){
			throw new Exception($db->error);
		}
		if(!move_uploaded_file($_FILES['card']['tmp_name'], 'img/cardEdu/'.$fileName)){
			throw new Exception('move_uploaded_file failed');
		}
		
		$db->commit();
		View::display('message', array('message'=>'สมัคร hosting เรียบร้อยแล้ว โปรดรอการอนุมัติจากเจ้าหน้าที่', 'redir'=> 'old.php?page=user/invoice', 'sec'=> 4));
	} catch(Exception $ex) {
		$db->rollback();
		Log::error($ex);
		View::display('message', array('message'=> $ex->getMessage(), 'redir'=> 'old.php?page=education', 'sec'=> 2));
	}
}
else{
	View::display('education');
}